from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .models import Tenant, FormTemplate, FormSubmission, FormField, FormSection
import json
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.contrib import messages
import os
import uuid
from django.conf import settings

def home(request):
    """主页视图"""
    tenants = Tenant.objects.all()
    return render(request, 'forms_app/home.html', {'tenants': tenants})

@login_required
def form_list(request, tenant_id):
    tenant = get_object_or_404(Tenant, id=tenant_id)
    templates = FormTemplate.objects.filter(tenant_id=tenant_id)
    return render(request, 'forms_app/form_list.html', {
        'templates': templates,
        'tenant': tenant
    })

@login_required
def form_detail(request, template_id):
    template = get_object_or_404(FormTemplate, id=template_id)
    
    if request.method == 'POST':
        form_data = {}
        has_error = False
        
        # 处理表单数据
        for field in template.formfield_set.all():
            field_name = f'field_{field.id}'
            
            if field.field_type == 'image':
                if field.required and not request.FILES.getlist(field_name):
                    messages.error(request, f'请上传{field.label}')
                    has_error = True
                    continue
                    
                # 处理图片上传
                files = request.FILES.getlist(field_name)
                if files:
                    paths = []
                    for file in files:
                        path = handle_uploaded_file(file)
                        paths.append(path)
                    form_data[field_name] = paths
            else:
                value = request.POST.get(field_name)
                if field.required and not value:
                    messages.error(request, f'请填写{field.label}')
                    has_error = True
                    continue
                    
                # 处理复选框
                if field.field_type == 'checkbox':
                    value = request.POST.getlist(field_name)
                
                form_data[field_name] = value
        
        if not has_error:
            # 保存表单提交
            FormSubmission.objects.create(
                template=template,
                submitted_by=request.user,
                data=form_data
            )
            return redirect('submission_success', tenant_id=template.tenant.id)
    
    return render(request, 'forms_app/form_detail.html', {
        'template': template
    })

@login_required
def submission_success(request, tenant_id):
    return render(request, 'forms_app/submission_success.html', {
        'tenant_id': tenant_id
    })

def handle_uploaded_file(f):
    # 确保上传目录存在
    upload_dir = os.path.join(settings.MEDIA_ROOT, 'uploads')
    os.makedirs(upload_dir, exist_ok=True)
    
    # 生成唯一文件名
    filename = f"{uuid.uuid4().hex}{os.path.splitext(f.name)[1]}"
    file_path = os.path.join('uploads', filename)
    
    # 保存文件
    with open(os.path.join(settings.MEDIA_ROOT, file_path), 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
    
    return file_path

@login_required
def form_designer(request, tenant_id, template_id=None):
    tenant = get_object_or_404(Tenant, id=tenant_id)
    template = None
    
    if template_id:
        # 使用 select_related 和 prefetch_related 优化查询
        template = FormTemplate.objects.select_related('tenant').prefetch_related(
            'sections',
            'sections__formfield_set'
        ).get(id=template_id, tenant=tenant)
        
        # 获取所有字段组和字段数据用于调试
        sections_data = []
        for section in template.sections.all().order_by('order'):
            fields_data = []
            for field in section.formfield_set.all().order_by('order'):
                fields_data.append({
                    'label': field.label,
                    'type': field.field_type,
                    'required': field.required,
                    'options': field.options
                })
            sections_data.append({
                'title': section.title,
                'fields': fields_data
            })
        print("Template data:", {
            'id': template.id,
            'title': template.title,
            'sections': sections_data
        })
    
    return render(request, 'forms_app/form_designer.html', {
        'tenant': tenant,
        'form_template': template,
        'field_types': FormTemplate.FIELD_TYPES
    })

@login_required
@require_http_methods(['POST'])
def save_form_template(request, tenant_id):
    try:
        data = json.loads(request.body)
        tenant = get_object_or_404(Tenant, id=tenant_id)
        
        # 创建或更新表单模板
        if 'id' in data:
            template = get_object_or_404(FormTemplate, id=data['id'], tenant=tenant)
        else:
            template = FormTemplate(tenant=tenant)
        
        template.title = data['title']
        template.save()
        
        # 删除现有字段组和字段
        template.sections.all().delete()
        
        # 创建新字段组和字段
        for section_data in data['sections']:
            section = FormSection.objects.create(
                template=template,
                title=section_data['title'],
                order=section_data['order']
            )
            
            for field_data in section_data['fields']:
                # 确保选项值正确保存
                options = field_data['options']
                if options and isinstance(options, str):
                    options = options.strip()
                
                FormField.objects.create(
                    template=template,
                    section=section,
                    label=field_data['label'],
                    field_type=field_data['field_type'],
                    required=field_data['required'],
                    options=options,
                    order=field_data['order']
                )
        
        return JsonResponse({'success': True, 'template_id': template.id})
    except Exception as e:
        return JsonResponse({'success': False, 'error': str(e)}) 

@login_required
@require_http_methods(['POST'])
def delete_form_template(request, template_id):
    try:
        template = get_object_or_404(FormTemplate, id=template_id)
        
        # 检查权限
        if not (request.user.is_superuser or template.tenant in request.user.tenants.all()):
            return JsonResponse({
                'success': False, 
                'error': '您没有权限删除此表单'
            })

        # 删除表单
        template.delete()
        
        return JsonResponse({
            'success': True,
            'message': '表单已成功删除'
        })
        
    except FormTemplate.DoesNotExist:
        return JsonResponse({
            'success': False,
            'error': '表单不存在'
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': f'删除失败：{str(e)}'
        })

@login_required
def submission_list(request, template_id):
    template = get_object_or_404(FormTemplate, id=template_id)
    submissions = FormSubmission.objects.filter(
        template=template,
        submitted_by=request.user
    ).order_by('-submitted_at')
    
    return render(request, 'forms_app/submission_list.html', {
        'template': template,
        'submissions': submissions
    })

@login_required
def submission_detail(request, submission_id):
    submission = get_object_or_404(FormSubmission, id=submission_id)
    
    # 检查权限
    if submission.submitted_by != request.user and not request.user.is_superuser:
        messages.error(request, '您没有权限查看此提交记录')
        return redirect('form_list', tenant_id=submission.template.tenant.id)
    
    return render(request, 'forms_app/submission_detail.html', {
        'submission': submission
    }) 